<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="button" value="读取文件" onclick="read()">
<div id="result">
    <!--读取到的文件内容-->
</div>
<script>
    function getData() {
        const filename = "promise对象测试文件1.txt";
        return new Promise((resolve, reject) => {
            let objXmlHttp = new XMLHttpRequest();
            objXmlHttp.open("GET", filename, true);
            objXmlHttp.onreadystatechange = () => {
                try {
                    if (objXmlHttp.readyState === 4) {
                        if (objXmlHttp.status === 200) {
                            resolve(objXmlHttp.responseText);
                        }
                        else {
                            throw new Error("读取文件失败");
                        }
                    }
                } catch (err) {
                    reject(err);
                }
            };
            objXmlHttp.send();
        });
    }
    async function get() {
        return await getData();
    }
    function read() {
        get().then(response => {
            let result = document.getElementById("result");
            result.innerHTML = response;
        }).catch(err => console.log(err));
    }
</script>
</body>
</html>